package OrderService

import (
	"context"
	"gdshop-admin-go-api/app/request/OrderReq"
	"gdshop-admin-go-api/library/response"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"time"
)

func ChangeRemark(ctx context.Context, params *OrderReq.ChangeRemark) *response.JsonResponse {
	if params.Type != "remark" && params.Type != "seller_remark" {
		return response.FailByRequestMessage(nil, "未知类型")
	}
	orderModel := getOrderModel(ctx, params.OrderId)
	if orderModel == nil {
		return response.FailByRequestMessage(nil, "找不到订单")
	}
	modelMap := gconv.Map(orderModel)
	oldData := g.Map{
		params.Type: modelMap[params.Type],
	}
	newData := g.Map{
		params.Type: params.Remark,
	}
	err := g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		_, err := tx.Model("order").Where("id", params.OrderId).Update(newData)
		if err != nil {
			return err
		}

		_, err = tx.Model("order_log").Insert(g.Map{
			"type":      params.Type,
			"order_id":  params.OrderId,
			"admin_id":  params.AdminId,
			"member_id": 0,
			"old_data":  oldData,
			"new_data":  newData,
			"create_at": time.Now().Unix(),
		})
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	return response.SuccessByRequestMessage(nil, "成功")
}
